package com.amos.muexamclient.sys.controller;

import com.amos.bean.Result;
import com.amos.muexamclient.sys.service.SysPostService;
import com.amos.muexamclient.sys.service.SysRoleService;
import com.amos.muexamclient.sys.service.SysUserService;
import com.amos.muexamclient.sys.service.dto.SysPostDTO;
import com.amos.muexamclient.sys.service.dto.SysUserDTO;
import com.amos.muexamclient.util.SecurityUtils;
import com.amos.muexamcore.core.BasePageController;
import com.amos.muexamcore.core.BasePageService;
import com.amos.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * Copyright © 2018 五月工作室. All rights reserved.
 *
 * @Package com.amos.muexamclient.sys.controller
 * @ClassName SysUserController
 * @Description TODO
 * @Author Amos
 * @Modifier
 * @Date 2020-03-21 22:08:15
 * @Version 1.0
 **/
@RestController
@RequestMapping(value = "/sys/user")
public class SysUserController extends BasePageController<SysUserDTO> {
    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysRoleService roleService;
    @Autowired
    private SysPostService postService;

    @Override
    public BasePageService<SysUserDTO> getPageService() {
        return sysUserService;
    }

    @GetMapping(value = {"/", "/{userId}"})
    public Result getInfo(@PathVariable(value = "userId", required = false) String userId) {
        Map<String, Object> map = new HashMap<>();
        map.put("roles", roleService.optionSelect());
        map.put("posts", postService.select(new SysPostDTO()));
        if (StringUtils.isNullOrEmpty(userId)) {
            map.put("data", sysUserService.load(userId));
            map.put("postIds", postService.selectPostByUserId(userId));
            map.put("roleIds", roleService.selectRoleUserId(userId));
        }
        return Result.success(map);
    }

    @DeleteMapping("/{userIds}")
    public Result remove(@PathVariable("userIds") String[] userIds) {
        return Result.success(sysUserService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @PutMapping("/reset-pwd")
    public Result resetPwd(@RequestBody SysUserDTO user) {
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return Result.success(sysUserService.resetPwd(user));
    }

    @PutMapping("/change-status")
    public Result changeStatus(@RequestBody SysUserDTO user) {
        return Result.success(this.sysUserService.save(user));
    }
}
